package com.lyf.app.service.impl;

import com.lyf.app.entity.AppCategory;
import com.lyf.app.mapper.AppCategoryDao;
import com.lyf.app.service.AppCategoryService;
import com.lyf.app.vo.AppCategoryVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


@Service
public class AppCategoryServiceImpl implements AppCategoryService {


    @Autowired
    AppCategoryDao appCategoryDao;
    @Override
    public AppCategoryVO appCategoryTree() {

        List<AppCategoryVO> categoryVOS = new ArrayList<>();

        List<AppCategory> appCategories = appCategoryDao.queryAllBy(new AppCategory());

        for (AppCategory appCategory : appCategories) {
            AppCategoryVO appCategoryVO = new AppCategoryVO();
            BeanUtils.copyProperties(appCategory,appCategoryVO);
            categoryVOS.add(appCategoryVO);
        }

        AppCategoryVO appCategoryVO = new AppCategoryVO();
        for (AppCategoryVO categoryVO : categoryVOS) {
            if (categoryVO.getParentid()==null){
                appCategoryVO = treeChildren(categoryVO,categoryVOS);
            }
        }

        return appCategoryVO;
    }

    private AppCategoryVO treeChildren(AppCategoryVO categoryVO, List<AppCategoryVO> categoryVOS) {
        categoryVO.setChildren(new ArrayList<>());
        for (AppCategoryVO vo : categoryVOS) {
            if (categoryVO.getId()==vo.getParentid()){
                categoryVO.getChildren().add(vo);
                treeChildren(vo,categoryVOS);
            }
        }
        return categoryVO;
    }
}
